import 'package:bot_toast/bot_toast.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../../common/colors.dart';
import '../../../components/bottom_page.dart';
import '../../../services/address.dart';
import '../../../services/dio_manager.dart';
import '../../../utils/persisten_storage.dart';
import '../news_comment_detail_page.dart';
import '../news_detail_comment_model.dart';

class VideoCommentPage extends StatefulWidget {


  var newsId;


  VideoCommentPage(this.newsId);

  @override
  State<VideoCommentPage> createState() => _VideoCommentPageState();
}

class _VideoCommentPageState extends State<VideoCommentPage> {


  var commentList = [];
  final FocusNode _commentFocus = FocusNode();

  TextEditingController _tfEditingController = TextEditingController();

  /// 请求评论
  void requestComment()async{

    var params = {
      'page':1,
      'limit':'100',
      'id':widget.newsId
    };
    var json = await DioManager().
    kkRequest('${Address.host}/cms.news.comment/page/read',params: params,method: 'get');

    NewsDetailCommentModel model = NewsDetailCommentModel.fromJson(json);

    commentList = model.data!;


    setState(() {

    });
  }


  /// 发送评论
  void sendComment(String msg,String parentID)async{

    var params = {
      'news_id':'${widget.newsId}',
      'parent_id':'${parentID}',
      'comment':msg,
    };
    var json = await DioManager().kkRequest('${Address.homeHost}${Address.newsComment}',
        header: {'access_token': await PersistentStorage().getStorage('acctoken'),
          'user_id':await PersistentStorage().getStorage('uid'),
          'company_id':await PersistentStorage().getStorage('companyId')
        },
        bodyParams: params);

    if(json['errmsg'] == 'ok'){

      BotToast.showText(text: '${json['message']}');

      _tfEditingController.text = '';

      requestComment();

      // Get.back();

      // textKey.currentState!.setState(() {
      //
      // });

    }else{

    }
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    requestComment();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _commentFocus.unfocus();

  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration:BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(12.0)),

      ),
      height: 500,
      width: Get.width,
      child: Column(
        children: [
          Container(
            height: 35,
            margin: EdgeInsets.only(top: 15),
            child:Text('全部评论',style: TextStyle(fontWeight: FontWeight.w500),),
          ),
        Expanded(child: ListView(
            children: commentWidget(),
          )),

          Container(
            width: Get.width,
            height: 0.5,
            color:AppColor.lineColor,
          ),
          Container(
            height: 50+MediaQuery.of(context).padding.bottom,
            color: Colors.white,
            child: Row(
              children: [
                Center(
                  child:Container(
                    decoration: BoxDecoration(

                    ),
                    height: 30,
                    width: Get.width-70,

                    margin: EdgeInsets.only(left: 15,bottom: 15),
                    child: TextField(
                    controller: _tfEditingController,
                      focusNode: _commentFocus,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          hintText: '请输入评论1',
                          hintStyle: TextStyle(fontSize: 14)
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 15),
                  child:IconButton(onPressed: (){
                    sendComment(_tfEditingController.text, '0');
                    _commentFocus.unfocus();
                  },
                      icon: Icon(Icons.send,size: 20,color:AppColor.smallTextColor,)),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  List<Widget>commentWidget(){

    List<Widget> page = [];


    for(int i = 0;i<commentList.length;i++){

      // int likeStr = int.parse(widget.commentList[i]['fabulous_number']);
      //
      // Uint8List bytes = base64.decode(widget.commentList[i]['image_small']);

      NewsDetailCommentItemModel model = commentList[i];

      page.add(
          ListTile(
            title: Container(
              child: Row(
                mainAxisAlignment:MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      // Container(
                      //   clipBehavior: Clip.antiAlias,
                      //   margin: EdgeInsets.only(right: 10),
                      //   child: Image.memory(bytes,fit: BoxFit.cover,),
                      //   width: 25,
                      //   height: 25,
                      //   decoration: BoxDecoration(
                      //     borderRadius: BorderRadius.all(Radius.circular(25/2)),
                      //   ),
                      // ),
                      Text(
                        '${model.author}',style: TextStyle(fontSize: 12,fontWeight: FontWeight.w700),
                      ),
                    ],
                  ),
                  // IconTextButton.icon(
                  //     color: Colors.transparent,
                  //     elevation: 0,
                  //     onPressed: (){
                  //
                  //       // likeStr++;
                  //       // print(likeStr);
                  //       // setState(() {
                  //       //
                  //       // });
                  //
                  //     }, icon: Icon(Icons.favorite_outline_rounded,size: 15,), label: Text(likeStr.toString(),style: TextStyle(fontSize: 13),), iconTextAlignment: IconTextAlignment.iconRightTextLeft),
                  TextButton(
                      onPressed: (){
                        showDialog(
                            barrierDismissible: true,//是否点击空白区域关闭对话框,默认为true，可以关闭
                            context: context,
                            builder: (BuildContext context) {
                              var list = [];
                              list.add('色情低俗');
                              list.add('政治敏感');
                              list.add('广告');
                              list.add('令人恶心');
                              list.add('其他');
                              return BottomSheetWidget(
                                list: list,
                                onItemClickListener: (index) async {
                                  // LKToast.toast(context,msg: '举报成功，我们将随后处理您的举报');
                                  BotToast.showText(text: '举报成功，我们将随后处理您的举报');
                                  print( list[index]);
                                  Navigator.pop(context);
                                },
                              );
                            });
                      }, child: Text('举报',style: TextStyle(fontSize: 12),)),
                ],
              ),
            ),
            subtitle: Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(model.comment,style: TextStyle(fontSize: 15,color: Colors.black87),),
                  SizedBox(height: 20,),
                  Row(
                    children: [
                      Container(
                        // color: Colors.red,
                        child: Text(model.dateBeauty,style: TextStyle(fontSize: 10,color: Colors.grey),),
                      ),
                      // GestureDetector(
                      //   onTap: (){
                      //     // comment
                      //
                      //
                      //   },
                      //   child:Container(
                      //     alignment: Alignment.centerLeft,
                      //     margin: EdgeInsets.only(left: 15),
                      //     // color: Colors.yellow,
                      //     child: Text('回复',style: TextStyle(fontSize: 11,color: AppColor.smallTextColor),),
                      //   ),
                      // ),
                    ],
                  ),
                  model.children!.isEmpty?Container():Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(
                        Radius.circular(6.0),
                      ),
                      color: AppColor.bgColor,
                    ),
                    margin: EdgeInsets.only(top: 15),
                    padding: EdgeInsets.all(5),

                    constraints: BoxConstraints(
                        maxHeight: 100,
                        minHeight: 0
                    ),
                    child:GestureDetector(
                      onTap: (){
                        print('111');
                        Get.bottomSheet(NewsCommenDetailPage(model),
                            isScrollControlled: true);
                      },
                      child: ListView.builder(
                        padding: EdgeInsets.all(0),
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            margin: EdgeInsets.only(top: 5,bottom: 5),
                            // color: Colors.white,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text('${model.children![index]['author']}:',style: TextStyle(
                                        fontSize: 12,color: AppColor.textColor,fontWeight: FontWeight.w500
                                    ),),
                                    Container(
                                      // color: Colors.red,
                                      width: Get.width-150,
                                      child: Text('${model.children![index]['comment']}',style: TextStyle(
                                        fontSize: 12,overflow: TextOverflow.ellipsis,
                                      ),maxLines: 1,),
                                    )
                                  ],
                                ),

                              ],
                            ),
                          );
                        },itemCount:model.children!.isEmpty?0:model.children!.length>=  3?3:model.children!.length,),
                    ),
                  )
                ],
              ),
            ),

          )
      );
    }
    return page;
  }

}
